﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security;
using System.Runtime.InteropServices;

namespace SharedGenomics.Workbench.Views.WindowsForms
{
    /// <summary>
    /// This is a TextBox implementation that uses the System.Security.SecureString as its backing
    /// store instead of standard managed string instance. At no time, is a managed string instance
    /// used to hold a component of the textual entry.
    /// It does not display any text and relies on the 'PasswordChar' character to display the amount of
    /// characters entered. If no password char is defined, then an 'asterisk' is used.
    /// </summary>
    public partial class SecureTextBox : TextBox
    {
        #region Private Members

        private string _lastPasswordText;

        #endregion

        #region Constructors

        public SecureTextBox()
        {
            InitializeComponent();
            this.UseSystemPasswordChar = true;
        }

        #endregion

        #region Public properties

        public override string Text
        {
            get
            {
                this._lastPasswordText = base.Text;
                return new String(this.PasswordChar, base.Text.Length);
            }
            set
            {
                //TODO: throw InvalidOperationException?
                base.Text = value;
            }
        }

        /// <summary>
        /// The secure string instance captured so far.
        /// This is the preferred method of accessing the string contents.
        /// </summary>
        public SecureString SecureText
        {
            get
            {
                //return _secureEntry;
                string temp = this.Text;
                SecureString secText = new SecureString();

                if (this._lastPasswordText != null)
                {
                    foreach (char c in this._lastPasswordText)
                        secText.AppendChar(c);
                }

                secText.MakeReadOnly();
                return secText;
            }
        }

      
        #endregion
    }
}
